"""
Case Type   : datakit安装
Case Name   : 安装已存在插件
Create At   : 2025/4/21
Owner       : @lonely-dance
Description :
    1.查看插件是否存在
    2.安装已存在插件
    3.成功
Expect      :
    1.成功
    2.合理报错
    3.成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.datakit_api.CommonApi import CommonApi


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.com_sh = CommonSH()
        self.datakit_node = Node('Datakit_Root')
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotEqual("error", self.token)
        self.com_api = CommonApi(self.token)
        self.plugin_name = 'base-ops'
        self.package_path = os.path.join(macro.DATAKIT_INSTALL_PATH, "visualtool-plugin")
        self.jar_name = ''

    def test_base_ops(self):
        text = '----step1:查看BaseOps插件是否存在 expect:成功----'
        self.log.info(text)
        self.log.info('----备份插件jar包----')
        cmd = f'''cd {self.package_path}; cp {self.plugin_name}* {macro.DATAKIT_INSTALL_PATH}'''
        res = self.datakit_node.sh(cmd).result()
        self.log.info(res)
        self.assertEqual('', res, '备份插件jar包失败')
        response = self.com_api.get_system_plugins_list()
        self.log.info(response.json())
        self.assertIn(self.plugin_name, response.text, '插件不存在')

        text = '----step2:安装已存在的BaseOps插件 expect:成功----'
        self.log.info(text)
        cmd = f'''ls {macro.DATAKIT_INSTALL_PATH}|grep {self.plugin_name}'''
        self.jar_name = self.datakit_node.sh(cmd).result()
        self.log.info(self.jar_name)
        self.assertNotIn('No such file or directory', self.jar_name, '执行失败')
        self.log.info('----安装插件----')
        jar_path = os.path.join(self.package_path, self.jar_name)
        response = self.com_api.post_system_plugins_offline_install(jar_file=jar_path)
        self.log.info(response.json())
        self.assertIn('plugin install error', response.json()['msg'])

    def tearDown(self):
        self.log.info('----step3:清理环境 expect:成功----')
        cmd = f'rm -rf {macro.DATAKIT_INSTALL_PATH}/{self.plugin_name}*'
        res = self.datakit_node.sh(cmd).result()
        self.log.info(res)
        self.assertEqual('', res, '执行失败')
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
